package com.ruoyi.system.mapper.typeHandler;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

public class MapTypeHandler extends BaseTypeHandler<Map<String,String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Map<String,String> parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, JSONUtil.toJsonStr(parameter));
    }  
    
    @Override
    public Map<String,String> getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String jsonStr = rs.getString(columnName);
        return JSONUtil.toBean(jsonStr, Map.class);
    }

    @Override
    public Map<String, String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        if (json != null) {
            return JSONUtil.toBean(json, Map.class);
        }
        return null;
    }

    @Override
    public Map<String, String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        if (json != null) {
            return JSONUtil.toBean(json, Map.class);
        }
        return null;
    }
}